const Koa = require('koa');
const Router = require('koa-router');
const static  = require('koa-static');
const jwt = require('jsonwebtoken');
const parse = require('koa-bodyparser');
const {exec} = require('./db')

//实例化
const app = new Koa();
const router = new Router();
const key = "userInfo"


//中间件
app.use(parse());
app.use(router.routes());
app.use(static(__dirname + "/views"))

//验证是否登录的中间件
async function isLoading(ctx,next){
    const token = ctx.request.headers;
    if(token){
        if(jwt.verify(token,key)){
            next();
        }else{
            ctx.body = "登录标识时效已过"
        }
    }else{
        ctx.body = "请先登录"
    }
}

//验证权限的中间件
async function auth(ctx,next){
    const token = ctx.request.headers;
    const data = jwt.verify(token,key);
    const {userId} = data[0];
    if(userId == 0){
        next()
    }else{
        ctx.body = "权限不够"
    }
}


//注册接口
router.post("/register",async (ctx)=>{
    const {userName,password} = ctx.request.body;
    const data = await exec(`select * from  user where userName='${userName}'`)
    //大于0代表该用户存在
    if(data.length>0){
        //查询存在的账户用户名与密码是否匹配
        const datas = await exec(`select * from  user where userName='${userName}' and passWord='${password}'`);
        //大于0代表用户名与密码匹配
        if(datas.length>0){
            const token = jwt.sign({
                userName:datas[0].userName,
                userId:datas[0].userId
            },key,{
                //时效性
                expiresIn:"1h"
            })
            ctx.body = {
                message:"登录成功",
                token
            }
        }else{
            ctx.body = {
                message:"账号与密码不匹配"
            }
        }
    }else{
        //不存在则存储数据
        await exec (`insert into user (userName,passWord) values ('${userName}','${password}')`);
        //获取成员数据
        const datas = await exec(`select * from  user where userName='${userName}' and passWord='${password}'`);
        //转换为token值返回
        const token = jwt.sign({
            userName:datas[0].userName,
            userId:datas[0].userId
        },key,{
            //时效性
            expiresIn:"1h"
        })
        ctx.body = {
            message:"注册登录成功",
            token
        }
    }
})

//端口监听
app.listen(4567,()=>{
    console.log("http://127.0.0.1:4567")
})